#!/bin/bash

# Current dir is como-fscp-voter

make clean
make

# Set log file path
rm *.log
now=$(date +"%Y-%m-%d %H:%M:%S")
LOG_FILES=( "0-$now.log" "1-$now.log")

# Define server & client exec path
SERVER_EXEC="./como_fscp_voter"
CLIENT_EXEC="./client_sender"
DATA_SENDER_NUM=3

# Get current time
echo $now | tee -a "${LOG_FILES[0]}"

# 1. Run server

echo "Starting server..."
$SERVER_EXEC >> "${LOG_FILES[0]}" 2>&1 &
SERVER_PID=$!
echo "Server started with PID: $SERVER_PID" | tee -a "${LOG_FILES[0]}"
# Wait for server to start
sleep 4

# Calculate the future time point to run clients

# Time later (s)
TIME_LATER=5
# Sleep time (s)
SLEEP_TIME=25

FUTURE_TIME=$(date -d "+$TIME_LATER seconds" +"%Y %m %d %H %M %S")

# 2. Run clients

# Parse the future time into variables
read -r YEAR MONTH DAY HOUR MINUTE SECOND <<< "$FUTURE_TIME"
FORMATTED_FUTURE_TIME="$YEAR-$MONTH-$DAY $HOUR:$MINUTE:$SECOND"
echo "Starting clients at: $FORMATTED_FUTURE_TIME"

# Run clients at the future time
for i in {1..3}; do
    $CLIENT_EXEC -t 127.0.0.1 7711 $YEAR $MONTH $DAY $HOUR $MINUTE $SECOND >> "${LOG_FILES[1]}" 2>&1 &
done

echo "Sleeping $SLEEP_TIME s for clients' running..."
sleep $SLEEP_TIME

# 3. Terminate server
echo "Terminating server..."
kill $SERVER_PID | tee -a "${LOG_FILES[0]}"

# Log generated, <date+time>.log
